import React, { useRef, useState } from 'react';
import { Button, message } from 'antd';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, WalletOutlined, EditOutlined } from '@ant-design/icons';
import {
  addUser,
  queryUserList,
  removeUser,
  frozenUser,
  thawUser,
  updateUser,
  addWalletUser,
} from '@/services/user';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { UserListItem } from '@/services/API.d';
import { columnsUserListItem } from '@/services/Column.d';
import ProForm, { ModalForm, ProFormText, ProFormSelect, ProFormDigit } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';

/**
 * 充值节点
 * @param fields
 */
const handleWalletAdd = async (fields: UserListItem) => {
  const hide = message.loading('正在充值');
  try {
    const res = await addWalletUser(fields);
    hide();
    if (res.code === 200) {
      message.success(res.msg);
      return true;
    }
    message.error(res.msg);
    return false;
  } catch (error) {
    hide();
    message.error('充值失败，请重试！');
    return false;
  }
};

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: UserListItem) => {
  if (fields.password !== fields.rm_password) {
    message.error('两次密码不一致！');
    return false;
  }

  const hide = message.loading('正在添加');
  try {
    const res = await addUser({ ...fields });
    hide();
    if (res.code === 200) {
      message.success(res.msg);
      return true;
    }
    message.error(res.msg);
    return false;
  } catch (error) {
    hide();
    message.error('添加失败，请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: UserListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeUser(selectedRows.map((row) => row.carId));
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 *  冻结节点
 * @param selectedRows
 */
const handleFrozen = async (selectedRows: UserListItem[]) => {
  const hide = message.loading('正在冻结');
  if (!selectedRows) return true;

  try {
    await frozenUser(selectedRows.map((row) => row.carId));
    hide();
    message.success('冻结成功');
    return true;
  } catch (error) {
    hide();
    message.error('冻结失败，请重试');
    return false;
  }
};

/**
 *  解冻节点
 * @param selectedRows
 */
const handleThaw = async (selectedRows: UserListItem[]) => {
  const hide = message.loading('正在解冻');
  if (!selectedRows) return true;

  try {
    await thawUser(selectedRows.map((row) => row.carId));
    hide();
    message.success('解冻成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('解冻失败，请重试');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: UserListItem) => {
  const hide = message.loading('正在编辑');

  try {
    const res = await updateUser({ ...fields });
    hide();
    if (res.code === 200) {
      message.success(res.msg);
      return true;
    }
    message.error(res.msg);
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败请重试！');
    return false;
  }
};

const UserList: React.FC = () => {
  const [form] = useForm();
  const actionRef = useRef<ActionType>();
  const [carId, handleCarId] = useState<number>(0);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [walletModalVisible, handleWalletModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<UserListItem>();
  const [selectedRowsState, setSelectedRows] = useState<UserListItem[]>([]);
  const columns: ProColumns<UserListItem>[] = columnsUserListItem;
  columns[columns.length - 1].render = (_, record) => (
    <>
      <a
        onClick={() => {
          handleCarId(record.carId);
          handleWalletModalVisible(true);
        }}
      >
        <WalletOutlined />
        充值
      </a>
      &nbsp;&nbsp;
      <a
        onClick={() => {
          form.setFieldsValue(record);
          setCurrentRow(record);
          handleUpdateModalVisible(true);
        }}
      >
        <EditOutlined />
        编辑
      </a>
    </>
  );
  return (
    <PageContainer>
      <ProTable<UserListItem>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey={(record) => record.carId}
        search={{
          labelWidth: 120,
        }}
        pagination={{
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        dateFormatter="string"
        request={ async (params) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          let res: any = {};
          await queryUserList(params).then(v => {
            res = v;
            res.total = v.msg
          })
          return res;
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button
            type="primary"
            onClick={async () => {
              await handleFrozen(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量冻结
          </Button>
          <Button
            onClick={async () => {
              await handleThaw(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量解冻
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建用户"
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as UserListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          return true;
        }}
      >
        <ProFormText
          placeholder="请输入手机号"
          rules={[
            {
              required: true,
              message: '手机号为必填项',
            },
            {
              pattern: /^1\d{10}$/,
              message: '手机号格式错误！',
            },
          ]}
          width="md"
          name="tel"
        />
        <ProFormText.Password
          placeholder="请输入密码"
          rules={[
            {
              required: true,
              message: '密码为必填项',
            },
          ]}
          width="md"
          name="password"
        />
        <ProFormText.Password
          placeholder="重复密码"
          rules={[
            {
              required: true,
              message: '重复密码为必填项',
            },
          ]}
          width="md"
          name="rm_password"
        />
      </ModalForm>
      <ModalForm
        title="充值金额"
        width="400px"
        visible={walletModalVisible}
        onVisibleChange={handleWalletModalVisible}
        onFinish={async (value) => {
          const param = value as UserListItem;
          if (carId === 0) {
            message.error('充值失败');
            return false;
          }
          param.carId = carId;
          const success = await handleWalletAdd(param);
          if (success) {
            handleWalletModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          return true;
        }}
      >
        <ProFormDigit
          placeholder="请输入充值金额"
          rules={[
            {
              required: true,
              message: '请填写正确充值金额',
            },
          ]}
          width="md"
          name="overage"
        />
      </ModalForm>
      <ModalForm
        title="编辑用户"
        form={form}
        visible={updateModalVisible}
        onVisibleChange={handleUpdateModalVisible}
        onFinish={async (values) => {
          const success = await handleUpdate(values as UserListItem);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          return true;
        }}
      >
        <ProFormText name="carId" initialValue={currentRow?.carId} hidden={true} />
        <ProForm.Group>
          <ProFormText
            width="sm"
            name="tel"
            label="手机号"
            placeholder="请输入手机号"
            initialValue={currentRow && currentRow.tel}
            rules={[
              {
                required: true,
                message: '手机号为必填项',
              },
              {
                pattern: /^1\d{10}$/,
                message: '手机号格式错误！',
              },
            ]}
          />
          <ProFormText
            width="sm"
            name="carNumber"
            label="车牌号"
            placeholder="请输入车牌号"
            initialValue={currentRow && currentRow.carNumber}
            rules={[
              {
                required: true,
                message: '车牌号为必填项',
              },
            ]}
          />
          <ProFormText
            width="sm"
            name="parkingLot"
            label="是否停车"
            initialValue={currentRow && currentRow.parkingLot}
            disabled
            // placeholder="请输入是否停车"
            // rules={[
            //   {
            //     required: true,
            //     message: '是否停车为必选项填项',
            //   },
            // ]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            options={[
              {
                value: 1,
                label: '普通卡',
              },
              {
                value: 2,
                label: 'VIP卡',
              },
            ]}
            initialValue={currentRow && currentRow.cardType}
            width="sm"
            name="cardType"
            label="停车卡类型"
            rules={[
              {
                required: true,
                message: '停车卡类型为必选项',
              },
            ]}
          />
          <ProFormSelect
            width="sm"
            name="stationType"
            label="车位类型"
            placeholder="请选择车位类型"
            options={[
              {
                value: 1,
                label: '小型',
              },
              {
                value: 2,
                label: '中型',
              },
              {
                value: 3,
                label: '大型',
              },
            ]}
            initialValue={currentRow && currentRow.stationType}
            rules={[
              {
                required: true,
                message: '车位类型为必填项',
              },
            ]}
          />
          <ProFormSelect
            options={[
              {
                value: 1,
                label: '正常',
              },
              {
                value: 2,
                label: '冻结',
              },
              {
                value: 3,
                label: '欠费',
              },
            ]}
            initialValue={currentRow && currentRow.state}
            width="sm"
            name="state"
            label="状态"
            rules={[
              {
                required: true,
                message: '状态为必选项',
              },
            ]}
          />
          <ProFormText name="carId" initialValue={currentRow && currentRow.carId} hidden />
        </ProForm.Group>
      </ModalForm>
    </PageContainer>
  );
};

export default UserList;
